package com.qilu.pe.ui.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatEditText;

import com.alipay.sdk.app.PayTask;
import com.qilu.pe.R;
import com.qilu.pe.base.Base2Activity;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Config;
import com.qilu.pe.base.Global;
import com.qilu.pe.base.PayResult;
import com.qilu.pe.dao.bean.Doctor;
import com.qilu.pe.dao.bean.SettingData;
import com.qilu.pe.dao.bean.WxPayInfo;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.ActiviceCollector;
import com.qilu.pe.support.util.Logg;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.util.ToastUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.List;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class MyBalanceActivity extends Base2Activity {
    private RadioButton rb_ali, rb_wx;
    private RelativeLayout rl_ali, rl_wechat;
    private TextView tv_ok, tv_balance, tv_rule;
    private AppCompatEditText et_money;// 输入的充值金额

    private long money = 0L;// 记录充值金额
    String payType = "2";// 记录支付类型 1 微信 2 支付宝 3 银联

    IWXAPI msgApi;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_my_balance;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActiviceCollector.addActivity(this);
        rb_ali = findViewById(R.id.rb_ali);
        rb_wx = findViewById(R.id.rb_wx);
        rl_ali = findViewById(R.id.rl_ali);
        rl_wechat = findViewById(R.id.rl_wechat);
        tv_ok = findViewById(R.id.tv_ok);
        tv_balance = findViewById(R.id.tv_balance);
        tv_rule = findViewById(R.id.tv_rule);
        et_money = findViewById(R.id.et_money);

        setHeadTitle("账户充值");

        tv_balance.setText("¥" + Global.ORG_BALANCE);

        setListeners();

        msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(Config.WX_APP_ID);

        APIRetrofit.getDefault().getSetting(Global.HEADER).compose(RxUtil.<BaseResult2<SettingData>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<SettingData>>() {
                    @Override
                    public void accept(BaseResult2<SettingData> res) throws Exception {
                        if (res.isSuccess()) {
                            tv_rule.setText(String.format("规则：充值金额最低1000元，按1000元整数倍递增，充值额返%1$d\\%运费劵", res.getData().getFreeback()));
                        } else {
                            ToastUtils.showShort(res.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        reqUserInfo();// 请求用户信息,及时更新余额数据
    }

    // 获取用户信息
    private Disposable reqUserInfo() {
        return APIRetrofit.getDefault().getUserInfo(Global.HEADER, "1")
                .compose(RxUtil.<BaseResult2<List<Doctor>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<Doctor>>>() {
                    @Override
                    public void accept(BaseResult2<List<Doctor>> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {
                            List<Doctor> doctorList = result2.getData();
                            if (!isDataEmpty(doctorList)) {
                                Doctor doctor = doctorList.get(0);
                                Global.ORG_BALANCE = doctor.getMoney();
                                tv_balance.setText("¥" + Global.ORG_BALANCE);
                            }
                        } else {

                        }
                        Logg.i("reqUserInfo.result2.getMsg()" + result2.getMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private void setListeners() {
        setOnClickListener(rb_ali, rb_wx, rl_ali, rl_wechat, tv_ok);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == rl_ali || v == rb_ali) {
            rb_ali.setChecked(true);
            rb_wx.setChecked(false);
        }
        if (v == rl_wechat || v == rb_wx) {
            rb_ali.setChecked(false);
            rb_wx.setChecked(true);
        }
        if (v == tv_ok) {
            if (TextUtils.isEmpty(et_money.getText().toString().trim())) {
                ToastUtils.showShort("请输入充值金额");
                return;
            }
            money = Long.parseLong(et_money.getText().toString().trim());
            if (money <= 0 || money % 1000 != 0) {
                ToastUtils.showShort("充值金额应为1000的整数倍");
                return;
            }
            payType = rb_ali.isChecked() ? "2" : "1";
            if (rb_ali.isChecked()) {// 支付宝
                hideProgress();
                reqAliOrderInfo();
                showProgressWithText(true, "获取支付信息..");
            } else {// 微信
                hideProgress();
                reqWxOrderInfo();
                showProgressWithText(true, "获取支付信息..");
            }
        }
    }

    private Disposable reqWxOrderInfo() {
        return APIRetrofit.getDefault().reqRechargeWx(Global.HEADER, money, payType)
                .compose(RxUtil.<BaseResult2<WxPayInfo>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<WxPayInfo>>() {
                    @Override
                    public void accept(BaseResult2<WxPayInfo> baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            Logg.i("pay_data = " + baseResult2.getData());
                            WxPayInfo wxPayInfo = baseResult2.getData();
                            PayReq request = new PayReq();
                            request.appId = wxPayInfo.getAppid();
                            request.partnerId = wxPayInfo.getPartnerid();
                            request.prepayId = wxPayInfo.getPrepayid();
                            request.packageValue = "Sign=WXPay";
                            request.nonceStr = wxPayInfo.getNoncestr();
                            request.timeStamp = wxPayInfo.getTimestamp();
                            request.sign = wxPayInfo.getSign();
                            msgApi.sendReq(request);
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private Disposable reqAliOrderInfo() {
        return APIRetrofit.getDefault().reqRechargeAli(Global.HEADER, money, payType)// money 0.01
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            String orderInfo = (String) baseResult2.getData();
                            aliPay(orderInfo);
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // 支付宝支付
    private void aliPay(final String orderInfo) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(MyBalanceActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = 20100851;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        }).start();
    }

    @SuppressWarnings("all")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            //返回码，标识支付状态，含义如下：9000——订单支付成功 8000——正在处理中 4000——订单支付失败 5000——重复请求 6001——用户中途取消 6002——网络连接出错
            if (msg.what == 20100851) {
                PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                String payStatus = payResult.getResultStatus();
                if (TextUtils.equals(payStatus, "9000")) {// 判断resultStatus 为9000则代表支付成功
                    // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                    ToastUtils.showShort("支付成功");
                    paySuc();

                } else if (TextUtils.equals(payStatus, "6001")) {
                    ToastUtils.showShort("取消支付");
                } else {
                    // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                    ToastUtils.showShort("支付失败");
                }
            }
        }
    };

    private void paySuc() {
        Bundle bundle = new Bundle();
        bundle.putString("from", "recharge");
        startActivity(PaySuccessActivity.class, bundle);
    }
}